package urjc.as.emergencies.client.jpanels.missions;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Request;
import org.restlet.data.Response;

import net.miginfocom.swing.MigLayout;
import urjc.as.emergencies.client.CommToolkit;
import urjc.as.emergencies.client.DynamicTree;
import urjc.as.emergencies.client.Node;
import urjc.as.emergencies.client.TextArea;
import urjc.as.emergencies.data.Mission;
import urjc.as.emergencies.data.MissionList;

@SuppressWarnings("serial")
public class PanelMissions extends JPanel {
	private TextArea textArea;
	private MissionList missions;
	private DynamicTree tree;
	
	/**
	 * Create the panel.
	 */
	public PanelMissions(TextArea panelText, MissionList missions, DynamicTree _tree) {
		tree = _tree;
		textArea= panelText;
		this.missions = missions;
		setBorder(new TitledBorder(null, "Gestion Misiones", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
		setLayout(new MigLayout("", "[46px][][][][][][][][][][][][][][][][]", "[14px][][][][][][][][][][]"));
		
		JButton buttonNewMission = new JButton("Nueva Misión");
		buttonNewMission.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				newMission();
							
			}

			
		});
		add(buttonNewMission, "cell 0 0 17 11,alignx center");
		
		

	}
	
	private void newMission() {
		Mission mission = new Mission();
		
		String xml = mission.serializar();
		Request request = new Request(Method.POST, missions.getUri());
		request.setEntity(xml, MediaType.TEXT_XML);
		
		// Realizamos la petición
		Response resp = CommToolkit.doRequest(request);
		textArea.append(resp.getLocationRef().toString());
		//re paint the tree
		tree.redraw(resp.getLocationRef().toString(), Node.MISSION);
	}

}
